package com.nuatar.meibi.pubvar;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.nuatar.meibi.tool.PowerTool;

import android.os.Environment;
import android.util.Log;

public class NetBus {
	public static String Register(String did, String sid, String info) {
		return httpClientConn("action=SoftOpen&sid=" + sid + "&did=" + did
				+ "&info=" + info);
	}

	public static List<WallPaper> getWallPaper(String querystr) {
		List<WallPaper> list = new ArrayList<WallPaper>();

		String sources = httpClientConn(querystr);
		if (sources.length() > 5) {
			String[] strlist = sources.substring(1, sources.length()-1)
					.replace("#*", "~").split("~");
			for (int i = 0; i < strlist.length; i++) {
				WallPaper temp = ParseStringTowp(strlist[i]);
				list.add(temp);
			}
		}
		return list;
	}

	public static List<WallPaper> getHots() {
		return getWallPaper("action=getHot");
	}
	public static List<WallPaper> getHotsVIP() {
		return getWallPaper("action=getHotVIP");
	}
	public static List<WallPaper> getNew() {
		return getWallPaper("action=getNew");
	}
	public static List<WallPaper> getNewVIP() {
		return getWallPaper("action=getNewVIP");
	}
	public static List<WallPaper> getNewAt(String time) {
		return getWallPaper("action=getNewAt&time="+time);
	}
	public static List<WallPaper> getSortList(String sortid) {

		return getWallPaper("action=getSortList&sid=" + sortid);
	}

	public static String AddVc(String id) {
		return httpClientConn("action=AddView&wid=" + id);
	}

	public static List<SortList> getSorts() {
		List<SortList> result = new ArrayList<SortList>();
		String sourceList = httpClientConn("action=getSorts");
		String[] sortstr = sourceList.substring(1, sourceList.length() - 1)
				.replace("#*", "~").split("~");
		for (int i = 0; i < sortstr.length; i++) {
			SortList temp = new SortList();
			temp.setSortid(sortstr[i].split(",")[0]);
			temp.setTitle(sortstr[i].split(",")[1]);
			result.add(temp);
		}
		return result;
	}

	private static WallPaper ParseStringTowp(String wps) {
		WallPaper result = new WallPaper();
		String[] pss = wps.split(",");
		result.id = pss[0];
		result.title = pss[1];
		result.viewc = pss[2]!=null?pss[2]:"0";
		result.creatDate = pss[3];
		result.IsVIP=pss[4];
		return result;
	}

	public static boolean downloadDesFile(String id,ProgressMan pm) {

		String skey = PowerTool.getKey(Configer.Bucket, "GET", "/" + id + ".des",
				null);
		String url = Configer.BaseServer + Configer.Bucket+"/" + id
				+ ".des?sign=MBO:EBc9d7def393abe588e063fdd7db30ca:" + skey;
		String savePath = Environment.getExternalStorageDirectory().getPath()
				+ Configer.DirHead + id + "/" + id + ".des";

		if (httpDownload(url, savePath)) {
			ImagePair ip = PhoneMaster.getFirstImagePair(id);
			if (ip != null) {
				boolean bl= DownLoadLdtPart(id, ip,pm);
				return bl;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}

	public static boolean downloadLdtFile(String id) {
		String skey = PowerTool.getKey(Configer.Bucket, "GET", id + ".ldt", null);
		String url = Configer.BaseServer + "meik171/" + id
				+ ".ldt?sign=MBO:EBc9d7def393abe588e063fdd7db30ca:" + skey;
		String savePath = Environment.getExternalStorageDirectory().getPath()
				+ Configer.DirHead + id + "/" + id + ".ldt";
		return httpDownload(url, savePath);
	}

	public static boolean downloadBdtFile(String id) {
		String skey = PowerTool.getKey(Configer.Bucket, "GET", id + ".bdt", null);
		String url = Configer.BaseServer + "meik171/" + id
				+ ".bdt?sign=MBO:EBc9d7def393abe588e063fdd7db30ca:" + skey;
		String savePath = Environment.getExternalStorageDirectory().getPath()
				+ Configer.DirHead + id + "/" + id + ".bdt";
		return httpDownload(url, savePath);
	}

	public static List<SortList> getAllSortlist() {
		List<SortList> result = new ArrayList<SortList>();
		String sourceList = httpClientConn("action=getSorts");
		if (sourceList.length() >= 10) {
			String[] sortstr = sourceList.substring(1, sourceList.length() - 1)
					.replace("#*", "~").split("~");
			for (int i = 0; i < sortstr.length; i++) {
				SortList temp = new SortList();
				temp.setSortid(sortstr[i].split(",")[0]);
				temp.setTitle(sortstr[i].split(",")[1]);
				result.add(temp);

			}
		}
		return result;
	}

	public static String getCurrentTime() {
		String result = null;
		result = httpClientConn("action=getTime");
		return result;
	}

	public static void AddViews(String wid) {
		httpClientConn("action=AddViews");
	}

	public static boolean httpDownload(String httpUrl, String savePath) {
		boolean result;
		File sfile = new File(savePath);
		int lgn = 0;
		long d1=(new Date()).getTime();
		if (!sfile.exists()) {
			PrepareDir(savePath);
			@SuppressWarnings("unused")
			int bytesum = 0;
			int byteread = 0;
			URL url = null;
			try {
				url = new URL(httpUrl);
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
				result=false;
			}

			try {
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestMethod("GET");
				conn.addRequestProperty("User-Agent", "baidu-bcs-java-sdk/1");
				conn.setReadTimeout(60000);
				InputStream inStream = conn.getInputStream();
				ByteArrayOutputStream outstream = new ByteArrayOutputStream();
				byte[] buffer = new byte[1204];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					outstream.write(buffer, 0, byteread);
				}
				FileOutputStream fs = new FileOutputStream(savePath);
				fs.write(outstream.toByteArray());
				fs.flush();
				fs.close();
				inStream.close();
				result= true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				result= false;
			} catch (IOException e) {
				e.printStackTrace();
				result= false;
			}
		} else {
			result=true;
		}
		long d2=(new Date()).getTime();
		return result;

	}

	public static boolean DownLoadLdtPart(String id, ImagePair ip,ProgressMan pm) {
		boolean result;
		String savePath = PhoneMaster.getFilePathFromId(id, ".ldt");
		String httpUrl = PhoneMaster.getURLFromId(id, ".ldt");
		long dt1=(new Date()).getTime();
		File sfile = new File(savePath);
		if (!PhoneMaster.VerifyImage(savePath, ip)) {
			PrepareDir(savePath);
			int bytesum = 0;
			int byteread = 0;
			URL url = null;
			try {
				url = new URL(httpUrl);
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
				result= false;
			}

			try {
				HttpURLConnection conn1 = (HttpURLConnection) url
						.openConnection();
				conn1.setRequestMethod("GET");
				conn1.setReadTimeout(60000);
				int mom = conn1.getContentLength();
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestMethod("GET");
				conn.setReadTimeout(60000);
				conn.setRequestProperty("User-Agent", "baidu-bcs-java-sdk/1");
				conn.setRequestProperty("Range", "bytes=" + ip.Seeker + "-"
						+ (ip.Seeker + ip.Length - 1));
				InputStream inStream = conn.getInputStream();
				ByteArrayOutputStream outstream = new ByteArrayOutputStream();
				byte[] buffer = new byte[2048];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					outstream.write(buffer, 0, byteread);
					if(null!=pm){
						pm.Report(bytesum, mom);
					}
				}
				RandomAccessFile fs = new RandomAccessFile(savePath, "rw");
				fs.setLength(mom);
				fs.seek(ip.Seeker);
				fs.write(outstream.toByteArray());
				fs.close();
				inStream.close();
				if(ip.Md5.equals(PhoneMaster.getMd5(outstream.toByteArray()))){
					result= true;
				}else{
					result= false;
				}
			} catch (Exception e) {
				result= false;
			}
		} else {
			result= true;
		}
		return result;

	}

	public static String httpClientConn(String action) {
		String content = "";
		String ping = Configer.BaseURL + action;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// HttpGet
		HttpGet httpget = new HttpGet(ping);
		// ResponseHandler
		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		try {
			content = httpclient.execute(httpget, responseHandler);

		} catch (Exception e) {

			return "";
		}
		httpclient.getConnectionManager().shutdown();
		return content;
	}
	public static String httpClientConn(String baseURL, String action) {
		String content = "";
		String ping = baseURL + action;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// HttpGet
		HttpGet httpget = new HttpGet(ping);
		// ResponseHandler
		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		try {
			content = httpclient.execute(httpget, responseHandler);

		} catch (Exception e) {

			return "";
		}
		httpclient.getConnectionManager().shutdown();
		return content;
	}
	public static List<MyMsg> getMessage(String did,String time){
		List<MyMsg> result=null;
		String sources=httpClientConn(Configer.BaseMsg,"action=getMessage&did="+did+"&time="+time);
		if (sources.length() > 5) {
			result=new ArrayList<MyMsg>();
			String[] strlist = sources.substring(1, sources.length()-1)
					.replace("#*", "~").split("~");
			for (int i = 0; i < strlist.length; i++) {
				String[] pp=strlist[i].split(",");
				MyMsg temp=new MyMsg();
				temp.mid=pp[0];
				temp.info=pp[1];
				temp.time=pp[2];
				result.add(temp);
			}
		}
		return result;
	}
	private static void PrepareDir(String savePath) {
		File file = new File(savePath.substring(0, savePath.lastIndexOf('/')));
		if (!file.exists()) {
			if (file.mkdirs()) {
				Log.d("LiDir", "Dir creat success");
			} else {
				Log.e("Dir", "Dir creat fail");
			}
		} else {
			Log.i("Dir", "Dir exist");
		}
	}

	public interface ProgressMan {
		public void Report(int son, int mom);
		public void getError(Exception e);
	}
}
